package com.njtoyo.taxi.admin.service.business.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.library.payment.cmb.CmbPayClient;
import com.njtoyo.taxi.admin.logic.business.driver.DriverLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.OrderPaymentTableName;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.service.business.PassengerRefundService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
public class PassengerRefundServiceImpl implements PassengerRefundService {
    @Autowired
    private PassengerRefundMapper passengerRefundMapper;
    @Autowired
    private CallPrepayOrderMapper callPrepayOrderMapper;
    @Autowired
    private CallPrepayOrderRefundLogMapper callPrepayOrderRefundLogMapper;
    @Autowired
    private PassengerRefundLogMapper passengerRefundLogMapper;
    @Autowired
    private OrderPaymentMapper orderPaymentMapper;
    @Autowired
    private RideOrderMapper rideOrderMapper;
    @Autowired
    private RideMapper rideMapper;
    @Autowired
    private DriverLogic driverLogic;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public RestResult refund(Dict dict, AdminUser adminUser) {
        String number = dict.getStr("number");
        if (StrUtil.isBlank(number)) {
            return RestResult.failed("请输入查询交易单号");
        }
        Dict result = passengerRefundMapper.selectOneByNumber(number);
        if (ObjectUtil.isNull(result)) {
            return RestResult.failed("退款失败,交易单号记录未查询到");
        }
        String refundId = IdUtil.getSnowflake(1, 1).nextIdStr();
        String payNumber = result.getStr("payNumber");
        Long id = result.getLong("id");
        BigDecimal amount = result.getBigDecimal("amount");
        String txnAmtStr = Convert.toStr(amount.multiply(new BigDecimal(100)).intValue());
        //执行退款
        Map<String, String> refundMap = CmbPayClient.refund(refundId, payNumber, "订单取消-退款", payNumber, refundId, txnAmtStr, txnAmtStr);
        String respPreCode = MapUtil.getStr(refundMap, "respCode");
        if (!"SUCCESS".equals(respPreCode)) {
            log.info("乘客退款--失败,失败原因：{}", refundMap);
            return RestResult.failed("失败原因:" + MapUtil.getStr(refundMap, "respMsg"));
        }
        //保存预付款的退款记录
        callPrepayOrderRefundLogMapper.insert(new CallPrepayOrderRefundLog()
                .setOrderId(id)
                .setIsSuccess(true)
                .setRefundAmount(amount)
                .setRefundNumber(payNumber));
        //修改预付款退款状态
        callPrepayOrderMapper.updateById(new CallPrepayOrder().setId(id).setIsRefund(true).setRefundAmount(amount));


        passengerRefundLogMapper.insert(new PassengerRefundLog()
                .setOutTradeNumber(number)
                .setCallId(result.getInt("callId"))
                .setRefundAmount(amount)
                .setCreatedBy(adminUser.getId())
                .setCreatedAt(DateUtil.date()));

        return RestResult.success();
    }

    @Override
    public RestResult getOrderDetail(String keyword) {
        if (StrUtil.isBlank(keyword)) {
            return RestResult.failed("请输入查询单号");
        }
        if (StrUtil.contains(keyword, "R")) {
            if (!StrUtil.startWith(keyword, "P")) {
                RideOrder rideOrder = rideOrderMapper.selectOne(Wrappers.<RideOrder>lambdaQuery().eq(RideOrder::getNumber, keyword));
                if (ObjectUtil.isNull(rideOrder)) {
                    return RestResult.failed("查询失败,订单不存在");
                }
                Ride ride = rideMapper.selectById(rideOrder.getRideId());

                CallPrepayOrder callPrepayOrder = callPrepayOrderMapper.selectOne(Wrappers.<CallPrepayOrder>lambdaQuery().eq(CallPrepayOrder::getCallId, ride.getRefId())
                        .eq(CallPrepayOrder::getCallCategory, ride.getCategory().getCode()));
                keyword = callPrepayOrder.getNumber();
            }
        }

        OrderPayment orderPayment = orderPaymentMapper.selectOne(Wrappers.<OrderPayment>lambdaQuery()
                .eq(OrderPayment::getNumber, keyword)
                .or()
                .eq(OrderPayment::getOutTradeNumber, keyword));
        if (ObjectUtil.isNull(orderPayment)) {
            return RestResult.failed("查询失败,乘客可能还未付款");
        }
        if (!"wechat_cmb".equals(orderPayment.getPayChannel())) {
            return RestResult.failed("操作失败,此订单的付款渠道暂时不支持退款");
        }
        Dict resultDict = new Dict();
        if (orderPayment.getTableName() == OrderPaymentTableName.CallPrepayOrder) {
            CallPrepayOrder callPrepayOrder = callPrepayOrderMapper.selectById(orderPayment.getOrderId());
            Ride ride = rideMapper.selectOne(Wrappers.<Ride>lambdaQuery().eq(Ride::getRefId, callPrepayOrder.getCallId()));
            RideOrder rideOrder = rideOrderMapper.selectOne(Wrappers.<RideOrder>lambdaQuery().eq(RideOrder::getRideId, ride.getId()));
            BigDecimal driverBalance = driverLogic.getDriverBalance(ride.getDriverId());
            resultDict.put("driverBalance", driverBalance);
            resultDict.put("rideOrder", rideOrder);
            Driver driver = driverMapper.selectById(ride.getDriverId());
            resultDict.put("driver", driver);
            resultDict.put("ride", ride);
            User user = userMapper.selectById(ride.getUserId());
            resultDict.put("user", user);

        } else if (orderPayment.getTableName() == OrderPaymentTableName.RideOrder) {
            RideOrder rideOrder = rideOrderMapper.selectById(orderPayment.getOrderId());
            resultDict.put("rideOrder", rideOrder);
            Ride ride = rideMapper.selectById(rideOrder.getRideId());
            BigDecimal driverBalance = driverLogic.getDriverBalance(ride.getDriverId());
            resultDict.put("driverBalance", driverBalance);
            resultDict.put("rideOrder", rideOrder);
            Driver driver = driverMapper.selectById(ride.getDriverId());
            resultDict.put("driver", driver);
            resultDict.put("ride", ride);
            User user = userMapper.selectById(ride.getUserId());
            resultDict.put("user", user);
        }


        return RestResult.success(resultDict);
    }


}
